Skip to content

fix(analytics): avoid sending the same JavaScript-mode batch twice - #484

Draft
rahul-mixpanel wants to merge 2 commits into
masterfrom
rahulraveendran-sdk-251-react-native-283-duplicate-events
Draft

rahul-mixpanel wants to merge 2 commits into
masterfrom
rahulraveendran-sdk-251-react-native-283-duplicate-events

Conversation

@rahul-mixpanel

@rahul-mixpanel rahul-mixpanel commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In JavaScript mode (useNative: false, Expo, React Native Web), the event queue is shared by every Mixpanel instance for a token, but each instance runs its own flush timer. processQueue also starts the request without waiting for it. So the same batch was sent again before it was removed from the queue in these cases:

  • two instances exist for the same token (for example, new Mixpanel(...) inside a component, or React StrictMode mounting twice), and their timers fire together;
  • flush() is called while a timer flush is in flight;
  • a request takes longer than the 10s flush interval, including while sendRequest is in its own retry backoff (up to 5 retries, ~62s; mixpanel-network.js:101-118).

JavaScript mode adds no $insert_id, so the server ingests these duplicates. Overlapping flushes also each called spliceQueue for the same batch, so the second splice could delete events that had never been sent. This fits #283, which reports duplicate /track and /engage requests in an Expo app with useNative: false.

Fix

One flush per token and endpoint at a time, matching the native SDKs, which flush on a single worker:

  • Android: AnalyticsMessages.java:435-460 (one HandlerThread)
  • iOS: MixpanelInstance.swift:352 (serial networkQueue)

How it behaves:

  • A flush that starts while another is running is skipped, and that includes flush(). The running flush keeps draining the queue, including events added while it runs.
  • Stuck requests. React Native's Android fetch has no default timeout (OkHttp timeouts are 0), and sendRequest has no abort. So a request that never settles, such as a half-open connection after a network switch, would otherwise hold the lock for the rest of the session. A batch pending longer than 2 minutes (above the ~62s retry window) is treated as stuck, and the next flush takes over. The stuck flush then stops without touching the queue, so it can't remove events the new flush hasn't sent. At worst, the batch it was sending is sent once more, which is what master did on every interval.
  • Lock release. The batch loop releases the lock in a finally block, so an unexpected throw (storage, logging, or the 400 path's spliceQueue) can't leave it held.

Nothing changes in what's sent, the payloads, the request timeouts, the defaults or the public APIs.

Tests

  • __tests__/core.test.js has three new tests, and each fails without the fix:
    • two flushes while a request is in flight send once;
    • a request that never settles is taken over after the stale window, but not within it;
    • an unexpected throw releases the lock.
  • I also checked a scratch scenario with real queue and timers, not committed. Two MixpanelMain instances: before, 2 /track sends per event; after, 1. Slow network: 2 before, 1 after.
  • Full suite: 531 passed, 4 skipped.

Related to #283

🤖 Generated with Claude Code

In JavaScript mode the event queue is shared per token, but every Mixpanel
instance runs its own flush timer, and processQueue does not wait for the
request it starts. Two instances for the same token (for example one
created inside a component), a flush() during a timer flush, or a request
slower than the flush interval all sent the same batch again before it was
removed from the queue. JavaScript mode adds no $insert_id, so the
duplicates were ingested.

Allow one flush per token and endpoint at a time, like the native SDKs,
which flush on a single worker.

Related to #283

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@linear-code

linear-code Bot commented Nov 27, 2026

Copy link
Copy Markdown

SDK-251

@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5 · Do not merge until replacing an old lock can no longer resend a batch whose request is still active.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change affects JavaScript-mode queue sending across timer and manual flushes.

Do not merge until replacing an old lock can no longer resend a batch whose request is still active.

Findings

  1. P1 Slow requests send batches twice ▶
  2. P2 Test completes the wrong request ▶
Fix with agent prompt
### Issue 1
javascript/mixpanel-core.js:113-124
If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. `sendRequest` has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in `fetch` and `response.json()`. The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.

The `ownsLock()` check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.

### Issue 2
__tests__/core.test.js:139-146
Both queue mocks ignore the endpoint, and each request overwrites `finishRequest`. The first `flush()` starts all three endpoints, so `finishRequest()` completes `/groups/` and empties their shared fake queue. The test passes with `/track/` still pending, so it cannot catch a missing lock release after event delivery. Return data only for `MixpanelType.EVENTS`, resolve that request, and check that a later flush can send another event.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Diagram

sequenceDiagram
  participant Timer
  participant Core
  participant Network
  Timer->>Core: Flush queued batch
  Core->>Network: Start request
  Note over Network: Request or retries exceed two minutes
  Timer->>Core: Flush again
  Core->>Core: Replace lock
  Core->>Network: Send same batch again
  Network-->>Core: Original request settles
  Core->>Core: Old owner skips queue removal
Loading

Reviews (2) · Last reviewed commit: "fix(analytics): recover the JavaScript-m..." · Reviewed by Greptile

Comment thread javascript/mixpanel-core.js Resolved
Comment thread __tests__/core.test.js
Comment on lines +138 to +145
MixpanelQueueManager.getQueue.mockImplementation(() => [...queue]);
MixpanelQueueManager.spliceQueue.mockImplementation(async (t, ty, start, count) => {
queue.splice(start, count);
});
let finishRequest;
MixpanelNetwork.sendRequest.mockImplementation(
() => new Promise((resolve) => (finishRequest = resolve))
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test completes the wrong request

Both queue mocks ignore the endpoint, and each request overwrites finishRequest. The first flush() starts all three endpoints, so finishRequest() completes /groups/ and empties their shared fake queue. The test passes with /track/ still pending, so it cannot catch a missing lock release after event delivery. Return data only for MixpanelType.EVENTS, resolve that request, and check that a later flush can send another event.

Prompt To Fix With AI
This is a comment left during a code review.
Path: __tests__/core.test.js
Line: 138-145

Comment:
**Test completes the wrong request**

Both queue mocks ignore the endpoint, and each request overwrites `finishRequest`. The first `flush()` starts all three endpoints, so `finishRequest()` completes `/groups/` and empties their shared fake queue. The test passes with `/track/` still pending, so it cannot catch a missing lock release after event delivery. Return data only for `MixpanelType.EVENTS`, resolve that request, and check that a later flush can send another event.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

…failed flushes

Review follow-up. React Native's Android fetch has no default timeout, so a
request that never settles held the per-token flush lock for the rest of
the session. A batch pending longer than sendRequest's full retry window
(2 minutes, above the ~62s of backoff) now counts as stuck, and the next
flush takes over. A taken-over flush stops without removing events from
the queue.

The batch loop now releases the lock in a finally block, so an unexpected
throw (storage, logging, or the 400 path's spliceQueue) can't leave it
held. The lock key also uses a separator.

Related to #283

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment on lines +113 to +124
if (current && Date.now() - current.batchStartedAt < FLUSH_LOCK_STALE_MS) {
MixpanelLogger.log(token, `Flush already in progress for endpoint: ${type}`);
return;
}
if (current) {
MixpanelLogger.warn(
token,
`Previous flush for endpoint ${type} appears stuck, starting a new one.`
);
}
const lock = { batchStartedAt: Date.now() };
flushLocks.set(flushKey, lock);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Slow requests send batches twice

If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. sendRequest has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in fetch and response.json(). The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.

The ownsLock() check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.

Knowledge Base Used: Event delivery and persistence

Prompt To Fix With AI
This is a comment left during a code review.
Path: javascript/mixpanel-core.js
Line: 113-124

Comment:
**Slow requests send batches twice**

If a request takes longer than two minutes, a later timer flush replaces its lock and sends the same queued batch again. `sendRequest` has no timeout or cancellation, and its 62 seconds of backoff excludes time spent in `fetch` and `response.json()`. The old request can therefore still deliver or retry the batch, causing duplicate events or profile updates.

The `ownsLock()` check only stops the old request from removing records. Keep the lock until the request settles, or stop the old request and its retries before replacing it.

**Knowledge Base Used:** [Event delivery and persistence](https://app.greptile.com/-/switch-tenant?tenant=mixpanel&next=%2Fcustom-context%2Fknowledge-base%2Fmixpanel%2Fmixpanel-react-native%2F-%2Fdocs%2Fevent-delivery-and-persistence.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant